package com.ssy.wireless.web.controller;

import com.ssy.wireless.entity.Account;
import com.ssy.wireless.util.MD5;
import com.ssy.wireless.util.RespVo;
import com.ssy.wireless.web.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 * Created by cofey on 16/11/18.
 */
@RestController
@SessionAttributes("currUser")
public class AccountController extends AbstractController{
    @Autowired
    private AccountService accountService;

    @PostMapping("/login")
    public RespVo login(@RequestParam("loginUser") String loginUser,
                        @RequestParam("password") String password,
                        Model model) {
        Assert.hasLength(loginUser, "登录用户不能为空");
        Assert.hasLength(loginUser, "登录密码不能为空");
        Account account = accountService.login(loginUser, password);
        model.addAttribute("currUser", account);
        return RespVo.success();
    }

    @PostMapping("/updateUserPwd")
    public RespVo<String> updateUserPwd(@RequestParam("oldPassword") String oldPassword,
                                        @RequestParam("newPassword") String newPassword,
                                        @RequestParam("confirmPassword") String confirmPassword,
                                        Model model) {
        Account exitsAccount = getAccount();
        Assert.notNull(exitsAccount,"用户不存在");
        Assert.hasLength(oldPassword,"旧密码不能为空");
        Assert.isTrue(exitsAccount.getPassword().equals(MD5.getInstance().exec(oldPassword)),"旧密码不正确");
        Assert.hasLength(newPassword,"新密码不能为空");
        Assert.hasLength(confirmPassword,"确认密码不能为空");
        Assert.isTrue(newPassword.equals(confirmPassword),"两次输入的密码不一致");
        Account account = new Account();
        account.setId(exitsAccount.getId());
        account.setPassword(MD5.getInstance().exec(newPassword));
        accountService.updateUserPwd(account);
        exitsAccount.setPassword(account.getPassword());
        model.addAttribute("currUser", exitsAccount);
        return RespVo.success("修改成功");
    }
}
